<template>
  <div class="physical-exam-packages-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h3>体检套餐管理</h3>
          <el-button type="primary" :icon="Plus" @click="openDialog('add')">新增套餐</el-button>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" label-width="80px" :inline="true">
          <el-form-item label="套餐名称">
            <el-input v-model="searchForm.name" placeholder="输入套餐名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="目标人群">
            <el-input v-model="searchForm.targetGroup" placeholder="输入目标人群" clearable></el-input>
          </el-form-item>
          <el-form-item label="价格区间">
            <el-input-number v-model="searchForm.minPrice" :min="0" :precision="2" placeholder="最低价" style="width: 130px;"></el-input-number>
            <span class="separator">-</span>
            <el-input-number v-model="searchForm.maxPrice" :min="0" :precision="2" placeholder="最高价" style="width: 130px;"></el-input-number>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
            <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="filteredPackages"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column prop="id" label="套餐编号" width="120"></el-table-column>
        <el-table-column prop="name" label="套餐名称" min-width="180"></el-table-column>
        <el-table-column prop="targetGroup" label="目标人群" min-width="150"></el-table-column>
        <el-table-column prop="price" label="价格(元)" width="120">
          <template #default="scope">
            <span>{{ scope.row.price.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目数量" width="100">
          <template #default="scope">
            <el-tag>{{ sumExamItems(scope.row) }}项</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建日期" width="120"></el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button type="success" :icon="View" size="small" @click="viewPackageDetail(scope.row)">查看</el-button>
            <el-button type="primary" :icon="Edit" size="small" @click="openDialog('edit', scope.row)">编辑</el-button>
            <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredPackages.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 体检套餐表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增体检套餐' : '编辑体检套餐'"
      width="70%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="packageFormRef"
        :model="packageForm"
        :rules="packageFormRules"
        label-width="100px"
      >
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="packageForm.name" placeholder="请输入套餐名称"></el-input>
        </el-form-item>
        <el-form-item label="目标人群" prop="targetGroup">
          <el-input v-model="packageForm.targetGroup" placeholder="请输入目标人群"></el-input>
        </el-form-item>
        <el-form-item label="套餐价格" prop="price">
          <el-input-number v-model="packageForm.price" :min="0" :precision="2" style="width: 100%;"></el-input-number>
        </el-form-item>
        <el-form-item label="套餐描述" prop="description">
          <el-input v-model="packageForm.description" type="textarea" rows="3" placeholder="请输入套餐描述"></el-input>
        </el-form-item>
        <el-form-item label="套餐状态" prop="status">
          <el-select v-model="packageForm.status" placeholder="请选择状态" style="width: 100%;">
            <el-option label="在售" value="在售"></el-option>
            <el-option label="停售" value="停售"></el-option>
            <el-option label="规划中" value="规划中"></el-option>
          </el-select>
        </el-form-item>
        
        <!-- 检查项目分类 -->
        <el-divider content-position="left">检查项目</el-divider>
        
        <div v-for="(category, index) in packageForm.items" :key="index" class="category-section">
          <div class="category-header">
            <el-form-item :label="'分类名称'" :prop="`items[${index}].category`" :rules="{ required: true, message: '请输入分类名称', trigger: 'blur' }">
              <el-input v-model="category.category" placeholder="请输入分类名称"></el-input>
            </el-form-item>
            <el-button type="danger" :icon="Delete" circle @click="removeCategory(index)" v-if="packageForm.items.length > 1"></el-button>
          </div>
          
          <div class="items-list">
            <el-form-item label="检查项目" :prop="`items[${index}].items`" :rules="{ required: true, message: '至少添加一个检查项目', trigger: 'blur' }">
              <el-tag
                v-for="(item, idx) in category.items"
                :key="idx"
                closable
                @close="removeItem(index, idx)"
                class="item-tag"
              >
                {{ item }}
              </el-tag>
              <el-input
                v-if="inputVisible[index]"
                ref="inputRef"
                v-model="inputValue[index]"
                class="tag-input"
                size="small"
                @keyup.enter="confirmInput(index)"
                @blur="confirmInput(index)"
              ></el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(index)">+ 添加项目</el-button>
            </el-form-item>
          </div>
        </div>
        
        <div class="add-category">
          <el-button type="primary" plain :icon="Plus" @click="addCategory">添加检查分类</el-button>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 体检套餐详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="体检套餐详情"
      width="60%"
    >
      <div v-if="currentPackage" class="package-detail">
        <div class="detail-header">
          <h2>{{ currentPackage.name }}</h2>
          <el-tag :type="getStatusType(currentPackage.status)">{{ currentPackage.status }}</el-tag>
        </div>
        
        <div class="detail-info">
          <div class="info-item">
            <span class="label">套餐编号：</span>
            <span>{{ currentPackage.id }}</span>
          </div>
          <div class="info-item">
            <span class="label">目标人群：</span>
            <span>{{ currentPackage.targetGroup }}</span>
          </div>
          <div class="info-item">
            <span class="label">套餐价格：</span>
            <span class="price">¥{{ currentPackage.price.toFixed(2) }}</span>
          </div>
          <div class="info-item">
            <span class="label">创建日期：</span>
            <span>{{ currentPackage.createdAt }}</span>
          </div>
        </div>
        
        <div class="detail-description">
          <h3>套餐描述</h3>
          <p>{{ currentPackage.description }}</p>
        </div>
        
        <div class="detail-items">
          <h3>检查项目</h3>
          <el-collapse>
            <el-collapse-item v-for="(category, index) in currentPackage.items" :key="index" :title="category.category">
              <div class="item-list">
                <el-tag v-for="(item, idx) in category.items" :key="idx" class="item-tag">{{ item }}</el-tag>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { Search, Plus, Edit, Delete, Download, Refresh, View } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { physicalExamPackages } from '../../mock';

// 加载状态
const loading = ref(false);

// 体检套餐数据
const packageData = ref([]);

// 搜索条件
const searchForm = reactive({
  name: '',
  targetGroup: '',
  minPrice: null,
  maxPrice: null
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10
});

// 对话框状态
const dialogVisible = ref(false);
const dialogType = ref('add');
const detailDialogVisible = ref(false);
const currentPackage = ref(null);

// 添加新检查项目相关
const inputVisible = ref([]);
const inputValue = ref([]);
const inputRef = ref(null);

// 表单引用
const packageFormRef = ref(null);

// 表单数据
const packageForm = reactive({
  id: '',
  name: '',
  targetGroup: '',
  price: 0,
  description: '',
  status: '在售',
  items: [
    {
      category: '',
      items: []
    }
  ],
  createdAt: ''
});

// 表单验证规则
const packageFormRules = {
  name: [
    { required: true, message: '请输入套餐名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  targetGroup: [
    { required: true, message: '请输入目标人群', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入套餐价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于等于 0', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入套餐描述', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择套餐状态', trigger: 'change' }
  ]
};

// 筛选后的套餐数据
const filteredPackages = computed(() => {
  let result = [...packageData.value];
  
  if (searchForm.name) {
    result = result.filter(item => item.name.includes(searchForm.name));
  }
  
  if (searchForm.targetGroup) {
    result = result.filter(item => item.targetGroup.includes(searchForm.targetGroup));
  }
  
  if (searchForm.minPrice !== null && searchForm.minPrice !== undefined) {
    result = result.filter(item => item.price >= searchForm.minPrice);
  }
  
  if (searchForm.maxPrice !== null && searchForm.maxPrice !== undefined) {
    result = result.filter(item => item.price <= searchForm.maxPrice);
  }
  
  return result;
});

// 获取当前页数据
const paginatedData = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  const end = start + pagination.pageSize;
  return filteredPackages.value.slice(start, end);
});

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case '在售':
      return 'success';
    case '停售':
      return 'danger';
    case '规划中':
      return 'info';
    default:
      return 'warning';
  }
};

// 计算套餐检查项目总数
const sumExamItems = (row) => {
  return row.items.reduce((sum, category) => sum + category.items.length, 0);
};

// 初始化数据
onMounted(() => {
  fetchData();
});

// 获取体检套餐数据
const fetchData = () => {
  loading.value = true;
  try {
    // 这里使用mock数据，实际项目中应该是API请求
    packageData.value = physicalExamPackages;
  } catch (error) {
    console.error('获取体检套餐数据失败:', error);
    ElMessage.error('获取体检套餐数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1;
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  searchForm.minPrice = null;
  searchForm.maxPrice = null;
  handleSearch();
};

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val;
};

const handleCurrentChange = (val) => {
  pagination.currentPage = val;
};

// 打开对话框
const openDialog = (type, row) => {
  dialogType.value = type;
  
  if (type === 'add') {
    resetForm();
  } else if (type === 'edit' && row) {
    // 深拷贝数据，避免直接修改原数据
    Object.keys(packageForm).forEach(key => {
      if (key === 'items') {
        packageForm.items = JSON.parse(JSON.stringify(row.items || []));
      } else {
        packageForm[key] = row[key];
      }
    });
  }
  
  // 初始化输入状态数组
  inputVisible.value = Array(packageForm.items.length).fill(false);
  inputValue.value = Array(packageForm.items.length).fill('');
  
  dialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  packageForm.id = 'PE-' + Date.now().toString().substr(-6);
  packageForm.name = '';
  packageForm.targetGroup = '';
  packageForm.price = 0;
  packageForm.description = '';
  packageForm.status = '在售';
  packageForm.items = [
    {
      category: '',
      items: []
    }
  ];
  packageForm.createdAt = new Date().toISOString().substr(0, 10);
  
  if (packageFormRef.value) {
    packageFormRef.value.resetFields();
  }
};

// 添加分类
const addCategory = () => {
  packageForm.items.push({
    category: '',
    items: []
  });
  inputVisible.value.push(false);
  inputValue.value.push('');
};

// 移除分类
const removeCategory = (index) => {
  packageForm.items.splice(index, 1);
  inputVisible.value.splice(index, 1);
  inputValue.value.splice(index, 1);
};

// 显示输入框
const showInput = (index) => {
  inputVisible.value[index] = true;
  // 下一个渲染周期后聚焦
  setTimeout(() => {
    inputRef.value.focus();
  });
};

// 确认输入
const confirmInput = (index) => {
  if (inputValue.value[index]) {
    packageForm.items[index].items.push(inputValue.value[index]);
    inputValue.value[index] = '';
  }
  inputVisible.value[index] = false;
};

// 移除项目
const removeItem = (categoryIndex, itemIndex) => {
  packageForm.items[categoryIndex].items.splice(itemIndex, 1);
};

// 提交表单
const submitForm = () => {
  packageFormRef.value.validate((valid) => {
    if (valid) {
      if (dialogType.value === 'add') {
        // 添加新套餐
        packageData.value.unshift({...packageForm});
        ElMessage.success('新增体检套餐成功');
      } else {
        // 更新套餐
        const index = packageData.value.findIndex(item => item.id === packageForm.id);
        if (index !== -1) {
          packageData.value[index] = {...packageForm};
          ElMessage.success('更新体检套餐成功');
        }
      }
      dialogVisible.value = false;
    } else {
      return false;
    }
  });
};

// 删除套餐
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除体检套餐"${row.name}"吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = packageData.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      packageData.value.splice(index, 1);
      ElMessage.success('删除成功');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 查看套餐详情
const viewPackageDetail = (row) => {
  currentPackage.value = row;
  detailDialogVisible.value = true;
};
</script>

<style scoped>
.physical-exam-packages-container {
  padding: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
}

.search-area {
  margin-bottom: 20px;
}

.separator {
  margin: 0 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.category-section {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
  background-color: #f9fafc;
}

.category-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.category-header .el-form-item {
  margin-bottom: 0;
  flex: 1;
  margin-right: 16px;
}

.items-list {
  display: flex;
  flex-wrap: wrap;
}

.item-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.tag-input {
  width: 150px;
  display: inline-block;
  vertical-align: bottom;
}

.button-new-tag {
  margin-left: 8px;
}

.add-category {
  margin-bottom: 16px;
}

.package-detail {
  padding: 0 20px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.detail-header h2 {
  margin: 0;
  font-size: 22px;
}

.detail-info {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
}

.label {
  font-weight: bold;
  min-width: 100px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.detail-description, .detail-items {
  margin-bottom: 20px;
}

.detail-description h3, .detail-items h3 {
  font-size: 18px;
  margin-bottom: 10px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.item-list {
  display: flex;
  flex-wrap: wrap;
}
</style> 